const express = require('express');
const multer = require('multer');
const Buffer = require('Buffer');
const bodyParser = require('body-parser');
const cors = require('cors');
var fs = require('fs')

const app = express();

app.use(bodyParser.json());
app.use(cors());


function getRandomNumber(min, max) {
    // 计算范围内的随机数
    let random = Math.random() * (max - min + 1) + min;
    // 向下取整得到整数
    let randomNumber = Math.floor(random);
    // 返回随机数
    return randomNumber;
}

// 登录
app.post('/api/login', (req, res) => {

    let { userName, password } = req.body
    if (userName == 'admin' && password == '123456') {

        let obj = {
            "code": 0,
            "message": "登录成功",
            "data": {
                "token": "admin"
            }
        }
        res.send(obj);
    } else if (userName == 'vip' && password == '123456') {
        let obj = {
            "code": 0,
            "message": "登录成功",
            "data": {
                "token": "vip"
            }
        }
        res.send(obj);
    } else if (userName !== 'admin' && userName !== 'vip' && password == '123456') {
        let obj = {
            "code": 0,
            "message": "登录成功",
            "data": {
                "token": "other"
            }
        }
        res.send(obj);
    } else {
        let obj = {
            "code": 500,
            "message": "用户名或密码错误",
        }
        res.send(obj);
    }




});


// 获取菜单
app.post('/api/permission', (req, res) => {




    let token = req.get('Authorization')



    if (token == 'admin') {
        let obj = {
            "code": "0",
            "message": "获取权限成功",
            "data": [
                {
                    "name": "实验组织分系统",
                    children: [
                        {
                            "name": "实验组织模块",
                            children: [
                                {
                                    name: "新建"
                                },
                                {
                                    name: "实验管理"
                                },
                                {
                                    name: "进入实验"
                                },

                            ]
                        },
                        {
                            "name": "实验资源模块",
                            children: [
                                {
                                    name: "数据模型"
                                },
                                {
                                    name: "算法"
                                },
                                {
                                    name: "知识库"
                                },
                                {
                                    name: "地图数据"
                                },
                                {
                                    name: "用户数据"
                                },
                            ]
                        },
                        {
                            "name": "首页",
                            "noChildren": true
                        },
                        {
                            "name": "用户管理",
                            "children": [{
                                "name": "用户列表",
                                children: [{
                                    name: "添加用户"
                                },
                                {
                                    name: "删除用户",

                                }
                                ]
                            },]
                        },
                    ]
                },

                {
                    name: "用户管理",
                    children: [
                        {
                            name: "用户列表",
                            children: [
                                {
                                    name: "添加用户",
                                },
                                {
                                    name: "删除用户",
                                },
                            ]
                        },

                    ]
                }
            ]
        }
        res.send(obj);
    } else if (token == 'vip') {
        let obj = {
            "code": "0",
            "message": "获取权限成功",
            "data": [
                {
                    "name": "实验组织模块",
                    children: [
                        {
                            name: "新建"
                        },
                        {
                            name: "实验管理"
                        },
                        {
                            name: "进入实验"
                        },

                    ]
                },
                {
                    "name": "实验资源模块",
                    children: [
                        {
                            name: "数据模型"
                        },
                        {
                            name: "算法"
                        },
                        {
                            name: "知识库"
                        },
                        {
                            name: "地图数据"
                        },

                    ]
                },
                {
                    "name": "首页",
                    "noChildren": true
                },

            ]
        }
        res.send(obj);
    } else {
        let obj = {
            "code": "0",
            "message": "获取权限成功",
            "data": [{
                "name": "首页",
                "noChildren": true
            },

            ]
        }
        res.send(obj);
    }


});


// 获取权限列表
let authorityList = [
    {
        name: "实验组织分系统",
        id: 1,
        children: [
            {
                name: "实验组织模块",
                id: 11,

                children: [
                    {
                        name: "创建实验",
                        id: 111,
                    },
                    {
                        name: "实验管理",
                        id: 112,
                    },
                    {
                        name: "实验要求编辑",
                        id: 113,
                    },
                    {
                        name: "实验流程监控",
                        id: 114,
                    },
                    {
                        name: "实验任务监控",
                        id: 115,
                    },
                    {
                        name: "实验流程任务批复",
                        id: 116,
                    },
                    {
                        name: "我的实验任务与状态",
                        id: 117,
                    },
                    {
                        name: "实验成果数据管理",
                        id: 118,
                    },
                    {
                        name: "论坛创建",
                        id: 119,
                    },
                    {
                        name: "论坛管理",
                        id: 1110,
                    },
                ],
            },

            {
                name: "实验资源模块",
                id: 12,

                children: [
                    {
                        name: "数据模型管理",
                        id: 121,
                    },
                    {
                        name: "算法模型管理",
                        id: 122,
                    },
                    {
                        name: "知识库模型管理",
                        id: 123,
                    },
                    {
                        name: "场景数据管理",
                        id: 124,
                    },
                    {
                        name: "用户数据管理",
                        id: 125,
                    },
                ],
            },

            {
                name: "实验场景模块",
                id: 13,

                children: [
                    {
                        name: "创建场景",
                        id: 131,
                    },
                    {
                        name: "场景编辑",
                        id: 132,
                    },
                    {
                        name: "场景管理",
                        id: 133,
                    },
                ],
            },

            {
                name: "显示框架模块",
                id: 14,

                children: [
                    {
                        name: "综合显控管理",
                        id: 141,
                    },
                    {
                        name: "指控显控管理",
                        id: 142,
                    },
                    {
                        name: "实验显控管理",
                        id: 143,
                    },
                    {
                        name: "显控资源管理",
                        id: 144,
                    },
                ],
            },
        ],
    },
    {
        name: "作战筹划分系统",
        id: 2,
        children: [
            {
                name: "筹划产品模块",
                id: 21,
                children: [
                    {
                        name: "筹划方案创建",
                        id: 211,
                    },
                    {
                        name: "筹划方案管理",
                        id: 212,
                    },
                    {
                        name: "筹划流程监控",
                        id: 213,
                    },
                    {
                        name: "筹划方案批复",
                        id: 214,
                    },
                    {
                        name: "筹划方案下发",
                        id: 215,
                    },
                    {
                        name: "研讨",
                        id: 216,
                    },
                ],
            },

            {
                name: "战场分析模块",
                id: 22,
                children: [
                    {
                        name: "情报信息组织",
                        id: 221,
                    },
                    {
                        name: "联合三情分析",
                        id: 222,
                    },
                    {
                        name: "综合威胁分析",
                        id: 223,
                    },
                    {
                        name: "研讨",
                        id: 224,
                    },
                ],
            },

            {
                name: "作战初始计划模块",
                id: 23,
                children: [
                    {
                        name: "作战使命分析",
                        id: 231,
                    },
                    {
                        name: "初始计划制定",
                        id: 232,
                    },
                    {
                        name: "初始计划管理",
                        id: 233,
                    },
                    {
                        name: "研讨",
                        id: 234,
                    },
                ],
            },

            {
                name: "作战构想开发模块",
                id: 24,
                children: [
                    {
                        name: "联合任务分析",
                        id: 241,
                    },
                    {
                        name: "联合构想筹划",
                        id: 242,
                    },
                    {
                        name: "构想任务配置",
                        id: 243,
                    },
                    {
                        name: "研讨",
                        id: 244,
                    },
                ],
            },
        ],
    },

]
app.get('/api/authorityList', (req, res) => {

    let data = authorityList

    let obj = {
        "code": "0",
        "message": "获取权限成功",
        data: data
    }

    res.send(obj);
});


// 获取角色列表
function getIds(arr, ids) {
    arr.forEach(v => {
        if (v.children && v.children.length) {
            getIds(v.children, ids)
        }
        ids.push(v.id)
    })
    return ids
}
let glyAuthorityList = getIds(authorityList, [])

let roleList = [
    {
        name: "管理员",
        id: 1,
        icon: "icon-yingyongguanliyuanguanli",
        authorityList: glyAuthorityList,
        describe: "负责整个系统的数据管理、用户管理、实验管理"
    },

    {
        name: "运维人员",
        id: 2,
        icon: "icon-yunweirenyuan",
        authorityList: [121, 122],
        describe: "负责整个系统的数据、状态、服务等正常运行"
    },
    {
        name: "实验成员",
        id: 3,
        icon: "icon-chengyuan",
        authorityList: [141, 142],
        describe: "负责系统的实验运行，在实验过程中，不同的用户参与到实验不同阶段中所使用的权限将不同，界面展现也将不同，负责系统的实验运行，在实验过程中，不同的用户参与到实验不同阶段中所使用的权限将不同，界面展现也将不同，负责系统的实验运行，在实验过程中，不同的用户参与到实验不同阶段中所使用的权限将不同，界面展现也将不同，负责系统的实验运行，在实验过程中，不同的用户参与到实验不同阶段中所使用的权限将不同，界面展现也将不同负责系统的实验运行，在实验过程中，不同的用户参与到实验不同阶段中所使用的权限将不同，界面展现也将不同负责系统的实验运行，在实验过程中，不同的用户参与到实验不同阶段中所使用的权限将不同，界面展现也将不同"
    },

]

app.get('/api/roleList', (req, res) => {


    let data = roleList

    let obj = {
        "code": "0",
        "message": "获取权限成功",
        data: data
    }

    res.send(obj);
});

// 校验角色名
app.get('/api/roleCheck', (req, res) => {
    let userInfo = req.query

    let index = roleList.findIndex(v => {

        return v.name == userInfo.roleName
    })
    console.log(index);
    if (index == -1) {
        let obj = {
            "code": "0",
            "message": "未被注册",
            data: {
                respDesc: true
            }
        }
        res.send(obj);
    } else {
        let obj = {
            "code": "0",
            "message": "已被注册",
            data: {
                respDesc: false
            }
        }
        res.send(obj);
    }
});

// 添加角色

app.post('/api/addRole', (req, res) => {
    let userInfo = req.body
    let obj = {
        "code": "0",
        "message": "新增角色成功",
        data: {
            message: '新增角色成功'
        }
    }
    if (!userInfo.id) {
        userInfo.id = roleList.length + 1

        roleList.unshift({
            name: userInfo.roleName,
            describe: userInfo.describe,
            icon: "icon-chengyuan",
            authorityList: []
        })

        obj.message = '新增角色成功'
        obj.data.message = '新增角色成功'
    } else {

    }
    res.send(obj);
});

// 分配权限 Assign permissions

app.post('/api/assignPermissions', (req, res) => {

    let { roleId, authorityList } = req.body
    console.log(authorityList, 8585);
    let index = roleList.findIndex(r => r.id === roleId)
    if (index) {
        roleList[index].authorityList = authorityList
    }
    let obj = {
        "code": "0",
        "message": "权限分配成功",
        data: {
            message: '权限分配成功'
        }
    }

    res.send(obj);
});


app.get('/api/routers', (req, res) => {

    let data = [{
        id: 2,
        pid: 0,
        path: "/kcgl",
        name: "Kcgl",
        title: "课程管理",
        link: "kcgl"
    },
    {
        id: 3,
        pid: 2,
        path: "kccz",
        name: "Kccz",
        title: "课程操作",
        link: "/kcgl/kccz"
    },
    {
        id: 4,
        pid: 3,
        path: "kcsj",
        name: "Kcsj",
        title: "课程数据",
        link: "/kcgl/kccz/kcsj"
    },
    {
        id: 5,
        pid: 2,
        path: "kcadd",
        name: "Kcadd",
        title: "添加课程",
        link: "/kcgl/kcadd"
    },
    {
        id: 6,
        pid: 0,
        path: "/xsgl",
        name: "Xsgl",
        title: "学生管理",
        link: "xsgl"
    },
    {
        id: 7,
        pid: 6,
        path: "xscz",
        name: "Xscz",
        title: "学生操作",
        link: "/xsgl/xscz"
    },
    {
        id: 8,
        pid: 6,
        path: "xsadd",
        name: "Xsadd",
        title: "添加学生",
        link: "/xsgl/xsadd"
    },
    ]

    let obj = {
        "code": "0",
        "message": "获取权限成功",
        data: []
    }

    let adminAuth = [2, 3, 4, 5, 6, 7, 8]
    let vipAuth = [2, 3, 5, 6, 7, 8]

    let otherAuth = [2, 3, 6, 7]

    let token = req.get('Authorization')
    console.log(token);

    let routes = []



    if (token == 'admin') {

        adminAuth.map(v => {
            data.map(s => {
                if (s.id == v) {
                    routes.push(s)
                }
            })
        })
        obj.data = routes
        res.send(obj);
    } else if (token == 'vip') {
        console.log('vip111');
        vipAuth.map(v => {
            data.map(s => {
                if (s.id == v) {
                    routes.push(s)
                }
            })
        })
        obj.data = routes
        res.send(obj);
    } else {
        console.log('other2222');
        otherAuth.map(v => {
            data.map(s => {
                if (s.id == v) {
                    routes.push(s)
                }
            })
        })
        obj.data = routes
        res.send(obj);
    }


});


const XLSX = require('xlsx');

function readXlsToArray(filePath) {
    // 读取xls文件
    const workbook = XLSX.readFile(filePath);
    // 获取工作表名称列表
    const sheetNames = workbook.SheetNames;
    // 获取第一个工作表
    const sheet = workbook.Sheets[sheetNames[0]];
    // 将工作表转换为JSON对象数组
    const data = XLSX.utils.sheet_to_json(sheet);
    return data;
}


// 上传用户 

var upload = multer({ dest: 'upload/' });
function toEn(arrObj) {
    // 处理数据
    const mapInfo = {
        登录账号: 'userName',
        登录密码: 'password',
        用户编号: 'userNum',
        用户姓名: 'name',
        部门: 'division',
        角色: 'role',
        状态: 'status',

    }

    // 遍历原数据
    const newarr = arrObj.map((item) => {
        //定义一个空对象,重新定义数组中的每一项
        const obj = {}
        //获取中文键数组
        const chKeys = Object.keys(mapInfo)
        //遍历中文键数组
        chKeys.forEach((key) => {
            //获取英文键
            const enKey = mapInfo[key]
            //重新定义每一项
            obj[enKey] = item[key]
        })
        return obj
    })
    return newarr

}
app.post('/api/uploadUser', upload.single('myfile'), function (req, res, next) {
    var file = req.file;

    // console.log("名称：%s",file.originalname);
    // console.log("mime：%s",file.mimetype);
    //以下代码得到文件后缀
    var name = Buffer.from(file.originalname, "latin1").toString("utf8");
    console.log(name, 'name');
    nameArray = name.split('');
    var nameMime = [];
    l = nameArray.pop();
    nameMime.unshift(l);
    while (nameArray.length != 0 && l != '.') {
        l = nameArray.pop();
        nameMime.unshift(l);
    }
    //Mime是文件的后缀
    let Mime = nameMime.join('');
    console.log(Mime, 'Mime');


    //重命名文件 加上文件后缀
    fs.renameSync('./upload/' + file.filename, './upload/' + name);

    const filePath = `./upload/${name}`


    // 使用示例
    const array = readXlsToArray(filePath);

    let newArr = toEn(array)
    console.log(newArr, 898989);
    userList.unshift(...newArr)
    let obj = {
        "code": "0",
        "message": "上传成功",
        data: {
            "message": "上传成功",
        }

    }
    res.send(obj);
})

var upload = multer({ dest: 'upload/' });

//单文件上传获取信息  图片
app.post('/api/upload-single', upload.single('myfile'), function (req, res, next) {
    var file = req.file;
    console.log(file, 8888888888888);
    // console.log("名称：%s",file.originalname);
    // console.log("mime：%s",file.mimetype);
    //以下代码得到文件后缀
    var name = Buffer.from(file.originalname, "latin1").toString("utf8");
    console.log(name, 'name');
    nameArray = name.split('');
    var nameMime = [];
    l = nameArray.pop();
    nameMime.unshift(l);
    while (nameArray.length != 0 && l != '.') {
        l = nameArray.pop();
        nameMime.unshift(l);
    }
    //Mime是文件的后缀
    let Mime = nameMime.join('');
    console.log(Mime, 'Mime');

    let obj = {
        "code": "0",
        "message": "上传成功",

    }
    res.send(obj);
    //重命名文件 加上文件后缀
    fs.renameSync('./upload/' + file.filename, './upload/' + name);
})


// 用户列表
let userList = []
for (let i = 1; i < 50; i++) {
    userList.push({
        userName: "admin" + i,
        id: i,
        password: "123456",
        userNum: i,
        name: "张三" + i,
        division: getRandomNumber(1, 4),
        role: getRandomNumber(1, roleList.length),
        status: getRandomNumber(1, 3),

    })
}

app.get('/api/userList', (req, res) => {
    let userInfo = req.query
    let filteredData = []
    //都没有
    if (!userInfo.userName && !userInfo.role) {
        // console.log('全无')
        filteredData = userList
    } else if (userInfo.userName && !userInfo.role) {
        // console.log('有名无状态')
        filteredData = userList.filter(item => {
            return item.userName.indexOf(userInfo.userName) !== -1
        })
    } else if (!userInfo.userName && userInfo.role) {
        // console.log('无名有状态')
        filteredData = userList.filter(item => {
            return item.role == userInfo.role
        })
    } else if (userInfo.userName && userInfo.role) {
        // console.log('有名有类型')
        filteredData = userList.filter(item => {
            return item.userName.indexOf(userInfo.userName) !== -1 && item.role == userInfo.role
        })
    }

    if (!userInfo.currentPage && !userInfo.pageSize) {
        const total = filteredData.length
        let obj = {
            "code": "0",
            "message": "获取用户列表成功",
            data: {
                data: filteredData,
                total: total,
                
            }
        }
        res.send(obj);
    } else {
        const totalItems = filteredData.length;
        let pageNumber = parseInt(userInfo.currentPage)
        let pageSize = parseInt(userInfo.pageSize)



        const start = (pageNumber - 1) * pageSize
        const end = start + pageSize;
        const totalPages = Math.ceil(totalItems / pageSize);
        let items = []
        items = filteredData.slice(start, end);
        const total = filteredData.length
        let obj = {
            "code": "0",
            "message": "获取用户列表成功",
            data: {
                data: items,
                total: total,
                totalPages: totalPages
            }
        }
        let token = req.get('Authorization')
        let routes = []


        res.send(obj);

    }





});

// 校验用户名 userCheck
app.get('/api/userCheck', (req, res) => {
    let obj = {
        "code": "0",
        "message": "未被注册",
        data: {
            respDesc: null
        }

    }
    let userInfo = req.query
    console.log(userInfo);
    let index = userList.findIndex(v => v.userName == userInfo.userName)
    console.log(index);
    if (index == -1) {
        obj.data.respDesc = true
    } else {
        obj.data.respDesc = false
    }


    res.send(obj);
});

// 添加用户   userList

const modifyObjectById = (array, id, newProperties) => {
    const index = array.findIndex(obj => obj.id === id);
    if (index !== -1) {
        array[index] = Object.assign({}, array[index], newProperties);
    }
};

app.post('/api/addUser', (req, res) => {
    let userInfo = req.body
    let obj = {
        "code": "0",
        "message": "新增用户成功",
        data: {
            message: '新增用户成功'
        }
    }
    if (!userInfo.userNum) {
        userInfo.userNum = userList.length + 1
        userInfo.status = 2
        userList.unshift(userInfo)

        obj.message = '新增用户成功'
        obj.data.message = '新增用户成功'
    } else {

        modifyObjectById(userList, parseInt(userInfo.userNum), userInfo);
        obj.message = '用户修改成功'
        obj.data.message = '用户修改成功'
    }


    res.send(obj);
});

// 删除用户 


app.post('/api/delUser', (req, res) => {
    let userInfo = req.body
    console.log(userInfo, 'id');
    let index = userList.findIndex(v => v.id == parseInt(userInfo.id))
    console.log(index, 'index');
    if (index != -1) {
        userList.splice(index, 1)
        console.log(userList.length, '长度')
        let obj = {
            "code": "0",
            "message": "删除用户成功",
            data: {
                message: '删除用户成功'
            }
        }
        res.send(obj);
    }


});




// 定义POST请求的路由
app.post('/api', (req, res) => {
    console.log(req.body);
    res.send('Received POST request');
});

// 启动服务器
app.listen(8083, () => {
    console.log('Server started on port 8083');
});